<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '去约会',
  },
}
</route>

<template>
  <view class="relative">
    <z-paging 
      ref="pagingRefs" 
      v-model="dataList" 
      :default-page-size="10"
      :safe-area-inset-bottom="true"
      :refresher-complete-delay="500"
      :auto="false"
      @query="queryList"
    >
      <template #top>
        <!-- 导航 -->
        <!--  #ifdef MP-WEIXIN -->
        <wd-navbar 
          placeholder 
          safeAreaInsetTop 
          :title="themeConfig.title" 
          left-arrow 
          @click-left="back"
        ></wd-navbar>
        <!--  #endif -->
          
        <!-- 走马灯 -->
        <view class="w-750rpx m-a" v-if="isShowTips">
          <wd-notice-bar 
            text="在了解对方之前，不要透露过多个人信息，包括地址、电话号码等敏感信息。任何要求提供验证码或借钱的行为都可能是骗局，务必保持警惕‌。不去私密和不安全的约会场所，注意自身财产和人身安全，发生任何安全事故，责任自负。"
            :color="themeConfig.theme === 'dark' ? '#fff': '#1B1116'"
            background-color="rgba(255, 255, 255, 0)"
          >
            <template #prefix>
              <view class="w-32rpx h-32rpx font-size-0 pr-16rpx">
                <wd-img 
                  width="100%" 
                  height="100%" 
                  :src="tips" 
                  mode="aspectFill" 
                />
              </view>
            </template>
          </wd-notice-bar>
        </view>
        
        <view class="bg-#F7F8FA z-10"
          :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
        >
          <!-- 搜索框 -->
          <search-filter 
            inputWrapClass="" 
            placeholder="搜索关键词" 
            @handleClear="handleClear"
            @handleShowCity="toSelectAddress"
            @handleConfirm="handleSearchConfirm" 
            @handleSearch="handleSearchConfirm"
          >
            <template #address>
              <view class="font-size-24rpx flex items-center justify-end box-border pl-6rpx w-360rpx">
                <i class="iconfont icon-frame font-size-36rpx mr-8rpx color-#BBB"></i>
                <text class="ellipsis">
                  选择约会区域: {{ address || '全国' }}
                </text>
              </view>
            </template>
          </search-filter>
          
          <!-- 筛选条件 -->
          <view class="w-750rpx m-a flex-sb-center">
            <view class="w-center box-border pb-20rpx whitespace-nowrap relative flex-sb-center">
              <view class="h-38rpx rounded-38rpx inline-flex font-size-26rpx pl-18rpx pr-18rpx" 
                style="align-items: center;"
                :class="[{ 'selected color-white': item.typeCode === dateType }]"
                v-for="item in dateTypeList.showList" 
                :key="item.id"
                @click="handleChangeDateType(item.typeCode)"
              >{{ item.typeName }}</view>
              <view class="h-38rpx rounded-38rpx inline-flex font-size-26rpx pl-18rpx pr-18rpx relative" 
                :class="[{ 'selected color-white': dateTypeList.hideTypeCodeList.includes(dateType) }]"
                style="align-items: center;"
              >
                <text @click="handleChangeDateType()">更多</text>
                <view 
                  class="popover position-b-r !-bottom-12rpx w-145rpx rounded-8rpx pt-12rpx pb-12rpx pl-6rpx pr-6rpx bg-white z-10"
                  :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
                  v-if="isShowPopover"
                >
                  <block
                    v-for="(item, index) in dateTypeList.hideList"
                    :key="item.id"
                  >
                    <view 
                      class="text-center font-size-26rpx leading-32rpx mb-8rpx mt-8rpx color-#9C6DEF" 
                      :class="{ 'font-bold': dateType === item.typeCode }"
                      @click="handleChangeDateType(item.typeCode)"
                    >{{ item.typeName }}</view>
                    <view class="border-2px" v-if="(index+1) !== dateTypeList.hideList.length"></view>
                  </block>
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>

      <view class="w-full">
        <!-- 骨架屏 - 加载中 -->
        <view v-if="isFirst">
          <view class="w-750rpx m-a bg-#fff"
            :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
            v-for="item in 3"
            :key="item"
          >
            <view class="w-center flex pt-24rpx pb-24rpx">
              <wd-skeleton animation="gradient" :row-col="[{ size: '150rpx', type: 'circle' }]" />
              <wd-skeleton 
                animation="gradient" 
                :custom-style="{ width: '100%', marginLeft: '12px' }" 
                :row-col="[{ width: '100%' }, { width: '30%' }, { width: '50%' }]" 
              />
            </view>
            <view class="border-1px"></view>
          </view>
        </view>
        
        <!-- 加载中 -->
        <view class="flex-center py-50rpx" v-if="!isFirst && loading">
          <wd-loading size="32rpx" color="#9C6DEF" />
        </view>

        <appointment-item
          v-for="item in dataList"
          :key="item.id"
          :data="item"
          @end="handleEnd"
        />
      </view>
    </z-paging>
  </view>
</template>

<script lang="ts" setup>
import SearchFilter from "@/components/search/search-filter.vue";
import AppointmentItem from "@/components/list-item/appointment-item.vue";
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { useToast } from "wot-design-uni";
import { GetDatingInfoPage } from "@/service/db_love";
import { back } from '@/utils';
import { tips } from "@/static/base64";
import { share } from "@/enum";

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();
const common = computed(() => (useCommon.commonState));

const dateTypeList = computed(() => {
  const list = common.value.dictInfo.dateType || [];
  const _list = [{
    id: '1960623173395855668',
    typeCode: 'none',
    typeName: '全部',
    value: 'none',
    label: '全部',
    belongTo: 'dateType',
    belongToName: '约会类型',
  }, ...list]
  
  const showList = _list.filter((item, index) => index <= 4) || [];
  const hideList = _list.filter((item, index) => index > 4) || [];
  
  // 用于给 更多按钮的 判断
  const hideTypeCodeList = hideList.map(item => item.typeCode);
  return {
    showList, // 显示的集合
    hideList, // 气泡显示的集合
    hideTypeCodeList
  }
})

/**
 * 请求payload参数
 */
const pagination = reactive<AnyObj>({});
const dataList = ref([]);
const pagingRefs = ref();
const isFirst = ref(true);
const loading = ref(false);
const queryList = async (pageNo, pageSize) => {
  try {
    loading.value = true;
    const _pagination = JSON.parse(JSON.stringify(pagination));
    if (_pagination.datingType === 'none') {
      _pagination.datingType = undefined;
    }
    const { data } = await GetDatingInfoPage(_pagination, {
      pageNum: pageNo,
      pageSize,
    });
    isFirst.value = false;
    loading.value = false;
    const list = data.records || [];
    pagingRefs.value.complete(list);
  } catch (error) {
    loading.value = false;
    pagingRefs.value.complete(false);
    isFirst.value = false;
  }
}

const dateType = ref<string>('none');
const isShowPopover = ref(false); // 是否显示剩余筛选的判断
const handleChangeDateType = (typeCode: string = '') => {
  // 点击更多，显示或隐藏剩余筛选集合
  if (typeCode === '') {
    isShowPopover.value = !isShowPopover.value;
    return
  }
  // 隐藏剩余筛选类型的气泡框
  isShowPopover.value = false;
  // 当前选中的筛选类型相同，不触发事件
  if (dateType.value === typeCode) return;

  dateType.value = typeCode;
  pagination.datingType = typeCode === 'none' ? undefined : typeCode;
  pagingRefs.value.reload();
}

const handleSearchConfirm = (keyword) => {
  pagination.keyword = keyword;
  pagingRefs.value.reload();
}

// 约会结束提示
const handleEnd = () => {
  toast.show({ msg: '约会已结束!', duration: 3000 });
}

const handleClear = () => {
  address.value = '';
  dateType.value = '';
  
  for (const key in pagination) {
    delete pagination[key];
  }
  pagingRefs.value.reload();
}

// 选择地址相关
const address = ref('');
// 去选择地区页面
const toSelectAddress = () => {
  const { provinceId, cityId, districtId } = pagination || {};
  const list = [provinceId, cityId, districtId].filter(item => !!item);
  uni.navigateTo({
    url: '/feature/areaPicker?areaStr=' + list.join(','),
  })
}
// 更新城市
function handleUpdateArea(data) {
  setTimeout(() => {
    if (!data) {
      address.value = '';
      Object.assign(pagination, {
        provinceId: undefined, 
        cityId: undefined, 
        districtId: undefined
      })
      pagingRefs.value.reload();
      return
    }
    
    const [valStr, labelStr] = data.split('/');
    const [provinceVal, cityVal, districtVal] = valStr.split(',');
    const labelList = labelStr.split(',').filter(item => !!item);
    
    const addressList = labelList.slice(-2);
    address.value = addressList.join('');
    Object.assign(pagination, {
      provinceId: provinceVal, 
      cityId: cityVal, 
      districtId: districtVal
    })
    pagingRefs.value.reload();
  }, 0)
}

onLoad(() => {
  uni.$on('updateArea', handleUpdateArea);
  setTimeout(() => {
    pagingRefs.value.reload();
  }, 100)
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
})

const isShowTips = ref(false);
onHide(() => {
  isShowTips.value = false;
})

onShow(() => {
  isShowTips.value = true;
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '约会';
    setTimeout(() => {
      if (useCommon.refresh.appointmentDetail) {
        useCommon.refresh.appointmentDetail = false;
        pagingRefs.value.refresh();
      }
    }, 100)
  })
})

// 分享
onShareAppMessage(() => {
  const id = user.userInfo.id || '';
  return {
    title: '我满心期待，与你相遇的未来！',
    path: `/pages/tabbar/index?instrId=${id}`,
    imageUrl: share
  }
})
</script>

<style lang="scss" scoped>
:deep(.wd-popup) {
  z-index: 999 !important;
}

.popover {
  border: 3rpx solid #986DF0;
}

:deep(.wd-notice-bar) {
  padding-right: 0 !important;
}

.selected {
  background: linear-gradient( 180deg, #9C6DEF 0%, #E5C4FF 100%);
}
</style>
  